<?php

/**
 * 轮播图管理
 */
class TurnImgController extends AuthController {

	private $model;

	public function __init() {
		$this -> model = K('ImgConfig');
	}

	public function index() {
		$count = $this -> model -> count();
		$page = new Page($count, 15, 10);
		$imgs = $this -> model -> order('sort DESC') -> limit($page -> limit()) -> all();
		$this -> assign('imgs', $imgs);
		$this -> assign('page', $page -> show(3));
		$this -> display();
	}
	
	/**
	 * 编辑轮播图
	 */
	public function editImg(){
		if(IS_POST){
			//表示有图片上传
			if($_FILES['imgpath']['error']!=4){
				$width = Q('post.width');
				$height = Q('post.height');
				$upload = new Upload('Upload/Turnimg/' . date('y/m'));
				$data = current($upload -> upload());
				if (empty($data)) {
					$this -> error('图片上传失败');
				} else {
					//来这个地方可以缩略图处理
					$img = new Image();
	
					$bigPath = $data['dir'] . $data['filename']. '.'. $data['ext'];
	
					$listimg = $img -> thumb($data['path'], $bigPath, $width, $height, 6);
					//删除原图
					$_POST['imgpath'] = $bigPath;
					//删除旧图片
					unlink(Q('post.oldimg'));
				}
				
			}else{
				//如果没有上传图片那就不上做上传动作
				$_POST['imgpath'] = Q('post.oldimg','','strval');
			}
			if($this->model->editImg()){
				$this->success('修改成功',U('TurnImg/index'));
			}else{
				$this->error('修改失败');
			}
		}
		$iid = Q('get.iid',0,'intval');
		$img = $this->model->where('iid='.$iid)->find();
		p($img);
		$this->assign('img',$img);
		$this->display();
	}
	
	
	
	
	/**
	 * 删除一个轮播图
	 */
	 public function delImg(){
	 	$iid = Q('get.iid',0,'intval');
		if($this->model->delImg($iid)){
			$this->success('删除成功',U('TurnImg/index'));
		}else{
			$this->error($this->model->error);
		}
	 }
	
	
	/**
	 * 添加轮播图
	 */
	public function addImg() {
		if (IS_POST) {
			$width = Q('post.width');
			$height = Q('post.height');
			$upload = new Upload('Upload/Turnimg/' . date('y/m'));
			$data = current($upload -> upload());
			if (empty($data)) {
				$this -> error('图片上传失败');
			} else {
				//来这个地方可以缩略图处理
				$img = new Image();

				$bigPath = $data['dir'] . $data['filename']. '.'. $data['ext'];

				$listimg = $img -> thumb($data['path'], $bigPath, $width, $height, 6);
				//删除原图
				$_POST['imgpath'] = $bigPath;
				if ($this -> model -> addImg()) {
					$this -> success('轮播图添加成功',U('TurnImg/index'));
				} else {
					$this-> error ($this->model->error);
				}

			}
		}

		$this -> display();
	}

}
